<template>
	<view :class="isResponse ? 'response' : ''">
        <u-upload
            :fileList="fileList"
            @afterRead="afterRead"
            @delete="deletePic"
            multiple
			v-bind="$attrs"
        ></u-upload>
	</view>
</template>

<script>
	import config from '@/config'
    import {
		getAccessToken,
		getTenantId
	} from '@/utils/auth'
	export default {
		model: {
			prop: 'modelValue', // 对应 props msg
			event: 'update:modelValue'
		},
		props: {
			modelValue: {
				type: String
			},
			isResponse: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
                fileList: [],
			};
		},
		computed: {
		},
		watch: {
            fileList: {
                handler(newVal,oldVal) {
                    const newModelValue = newVal.filter(item=>item.status !== 'uploading').map(item=>item.url)
                    this.$emit('update:modelValue', newModelValue.join(','))
                }
            },
            modelValue: {
				immediate: true,
                handler(newVal,oldVal) {
					console.log('%c [ this.modelValue ]-51', 'font-size:13px; background:#588334; color:#9cc778;', this.modelValue)
                    const modelValueArray = this.modelValue ? this.modelValue.split(',') : []
                    modelValueArray.forEach(item=>{
                        const findIndex = this.fileList.findIndex(file=>file.url === item)
                        if(findIndex === -1) {
                            this.fileList.push({
                                url: item,
                            })
                        }
                    })
                    this.fileList.forEach(item=>{
                        const findIndex = modelValueArray.findIndex(url=>url === item.url)
                        if(findIndex === -1) {
                            this.fileList.splice(findIndex, 1)
                        }
                    })
                }
            }
		},
		mounted() {
			
		},
		methods: {
            // 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				const newFileList = [...this.fileList]
				lists.map((item) => {
					newFileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = newFileList[fileListLen]
					newFileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				this.fileList = newFileList
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: config.uploadUrl,
						filePath: url,
                        header: {
                            'Authorization': 'Bearer ' + getAccessToken(),
                            'tenant-id': getTenantId()
                        },
						name: 'file',
						formData: {
                            biz: 'temp' //这个属性用于控制文件上传的业务路径
						},
						success: (res) => {
                            const relust = JSON.parse(res.data)
                            resolve(relust.data)
						}
					});
				})
			},
		},
	}
</script>

<style lang="scss">
</style>